package cn.shoptnt.service.trade.order.command.impl;

import cn.shoptnt.client.goods.GoodsQuantityClient;
import cn.shoptnt.framework.context.ApplicationContextHolder;
import cn.shoptnt.model.goods.enums.QuantityType;
import cn.shoptnt.model.goods.vo.GoodsQuantityVO;
import cn.shoptnt.model.trade.order.dto.OrderDTO;
import cn.shoptnt.model.trade.order.vo.CommandResult;
import cn.shoptnt.model.trade.order.vo.OrderSkuVO;
import cn.shoptnt.service.trade.order.command.OrderCreateCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 订单信息入库命令执行器
 *
 * @author dmy
 * @version 1.0
 * 2022-01-15
 */
@Service
public class StockDeductCommand implements OrderCreateCommand {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private GoodsQuantityClient goodsQuantityClient;


    @Override
    public CommandResult execute(OrderDTO order) {
        //构建默认执行结果
        CommandResult result = new CommandResult(true, "成功!");
        result.setRollback(this, order);
        try {
            //获取订单中的商品sku信息集合
            List<OrderSkuVO> skuList = order.getOrderSkuList();
            //根据订单中的商品sku信息集合构建要扣减的库存列表
            List<GoodsQuantityVO> goodsQuantityList = buildQuantityList(skuList);

            //扣减正常库存，注意：如果不成功，库存在脚本里已经回滚，程序不需要回滚
            boolean lockStockResult = goodsQuantityClient.updateSkuQuantity(goodsQuantityList);
            logger.debug("订单【" + order.getSn() + "】普通商品锁库存结果为：" + lockStockResult);

            if (!lockStockResult) {
                result.setResult(false);
                result.setErrorMessage("订单商品扣减库存失败");
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setResult(false);
            result.setErrorMessage("订单商品扣减库存失败");
        }


        return result;
    }

    @Override
    public void rollback(OrderDTO order) {
        //获取订单中的商品sku信息集合
        List<OrderSkuVO> skuList = order.getOrderSkuList();
        //根据订单中的商品sku信息集合构建要扣减的库存列表
        List<GoodsQuantityVO> goodsQuantityList = buildQuantityList(skuList);
        //循环转换库存扣减数量
        for (GoodsQuantityVO goodsQuantityVO : goodsQuantityList) {
            goodsQuantityVO.setQuantity(0 - goodsQuantityVO.getQuantity());
        }

        //恢复缓存中扣减的库存信息
        this.goodsQuantityClient.updateSkuQuantity(goodsQuantityList);
    }


    /**
     * 根据订单中的商品sku信息集合构建要扣减的库存列表
     *
     * @param skuList sku信息集合
     * @return
     */
    private List<GoodsQuantityVO> buildQuantityList(List<OrderSkuVO> skuList) {
        List<GoodsQuantityVO> goodsQuantityList = new ArrayList<>();

        //循环商品sku集合，得到要扣减库存的商品信息
        for (OrderSkuVO sku : skuList) {
            GoodsQuantityVO goodsQuantity = new GoodsQuantityVO();
            goodsQuantity.setSkuId(sku.getSkuId());
            goodsQuantity.setGoodsId(sku.getGoodsId());
            //因为是扣减库存，所以用0减去购买数量，扣减的库存数设置为负数
            goodsQuantity.setQuantity(0 - sku.getNum());
            //下单扣减的商品库存是可用库存
            goodsQuantity.setQuantityType(QuantityType.enable);
            //放入集合中
            goodsQuantityList.add(goodsQuantity);
        }

        return goodsQuantityList;
    }
}
